package com.sctvcloud.weiyuan.ui.activities;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.utils.GeneraLifeObser;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.sctvcloud.weiyuan.R;
import com.sctvcloud.weiyuan.application.Cache;
import com.sctvcloud.weiyuan.base.BaseActivity;
import com.sctvcloud.weiyuan.base.BaseFragment;
import com.sctvcloud.weiyuan.base.BaseTopTabFragmentActivity;
import com.sctvcloud.weiyuan.beans.FCityState;
import com.sctvcloud.weiyuan.beans.FUsers;
import com.sctvcloud.weiyuan.beans.InvitationRuleVo;
import com.sctvcloud.weiyuan.beans.MessageStateBean;
import com.sctvcloud.weiyuan.beans.ServiceCityListVo;
import com.sctvcloud.weiyuan.beans.ServiceConfigBean;
import com.sctvcloud.weiyuan.beans.UserInfoBean;
import com.sctvcloud.weiyuan.http.AbsListNetCallback;
import com.sctvcloud.weiyuan.http.AbsNetCallBack;
import com.sctvcloud.weiyuan.http.NetUtils;
import com.sctvcloud.weiyuan.http.ParamsEditor;
import com.sctvcloud.weiyuan.ui.adapter.TopicDeatilAdapter;
import com.sctvcloud.weiyuan.ui.dialog.ChooseCityFuncFragment;
import com.sctvcloud.weiyuan.ui.dialog.NetModeDiaFragment;
import com.sctvcloud.weiyuan.ui.fragment.HomeFragment;
import com.sctvcloud.weiyuan.ui.fragment.MineFragment;
import com.sctvcloud.weiyuan.ui.fragment.PlatFormFragment;
import com.sctvcloud.weiyuan.ui.fragment.RebllionFragment;
import com.sctvcloud.weiyuan.ui.fragment.ServiceFragment;
import com.sctvcloud.weiyuan.ui.manager.AdPictureManager;
import com.sctvcloud.weiyuan.ui.utils.CityContrastUtils;
import com.sctvcloud.weiyuan.ui.widget.BasePlayerView;
import com.sctvcloud.weiyuan.utils.ListTypeUtils;
import com.sctvcloud.weiyuan.utils.LocationUtils;
import com.sctvcloud.weiyuan.utils.UserManager;
import com.sctvcloud.weiyuan.utils.VersionUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;

import static com.sctvcloud.weiyuan.ui.dialog.NetModeDiaFragment.NO_TAG;
import static com.sctvcloud.weiyuan.ui.dialog.NetModeDiaFragment.OK_TAG;

/**
 * 主页
 */
public class MainActivity extends BaseTopTabFragmentActivity {


    private Handler handler;
    private static final int GET_AD_IMG = 0;
    private static final int TO_PLAY_VIDEO = 1001;
    private AdPictureManager adPicManager;
    private int currentTabIndex = 0;
    ArrayList<Pair<String, String>> pairs = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pairs.add(new Pair<>("页面", "导航"));
        pairs.add(new Pair<>("行为类型", "点击"));
//        setContentView(R.layout.activity_main);
//        ButterKnife.bind(this);
        SharedPreferencesUtil.setParam(this, "FLOAT_AD", true);
        addTab("首页", R.mipmap.icon_home_unsel,
                R.mipmap.icon_home_sel, HomeFragment.class, true);
        addTab("微平台", R.mipmap.icon_home_weipingtai_unsel,
                R.mipmap.icon_home_weipingtai_sel, PlatFormFragment.class, true);
        addTab("短视频", R.mipmap.all_icon_tabplay,
                R.mipmap.all_icon_tabplay, ServiceFragment.class, false);
        addTab("服务", R.mipmap.icon_home_service_unsel,
                R.mipmap.icon_home_service_sel, ServiceFragment.class, true);
        addTab("我的", R.mipmap.icon_home_mine_unsel,
                R.mipmap.icon_home_mine_sel, MineFragment.class, true);
        commit(R.color.colorFontSelect);
//        initData();
        initPush();
        /*********************启动定时获取启动页广告图片的进程***************************/
        adPicManager = new AdPictureManager(this);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg != null && msg.what == GET_AD_IMG) {
                    requestAd();
                }
            }
        };
        adPicManager.startAdService(handler, GET_AD_IMG);
        /******************************************************************8****/
//        getServiceConfig();
        initUserData();
        int versionCode = VersionUtil.getVersionCode(this);
        SharedPreferencesUtil.setParam(this, SplashActivity.APP_VERSION_KEY, versionCode);

        setCenterClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, VideoPlayViewActivity.class);
                startActivityForResult(intent, TO_PLAY_VIDEO);
                GridsumWebDissector.getInstance().trackEvent(MainActivity.this, "", "播放", "", 200, pairs);
            }
        });
    }

    private void requestAd() {
        adPicManager.requestAdPic(this + "");
    }

    /**
     * 初始化推送状态
     */
    private void initPush() {
        boolean isPush = (boolean) SharedPreferencesUtil.getParam(this, "PUSH_KEY", true);
        if (isPush) {
            //设置开启推送
            SharedPreferencesUtil.setParam(this, "PUSH_KEY", true);
            JPushInterface.resumePush(this);
            JPushInterface.setAlias(this, 0, "scgc2_0");
        } else {
            //停止推送服务
            JPushInterface.stopPush(this);
        }


    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

    }


    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//            bottom_lay.setVisibility(View.GONE);
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//            bottom_lay.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onTabChanged(int index,String title) {
        switch (index) {
            case 0: //首页
                currentTabIndex = index;
                GridsumWebDissector.getInstance().trackEvent(this, "", "首页", "", 200, pairs);
                break;
            case 1:  //报料
                currentTabIndex = index;
                GridsumWebDissector.getInstance().trackEvent(this, "", "投稿", "", 200, pairs);
                break;
            case 2:   //播放
                Intent intent = new Intent(this, VideoPlayViewActivity.class);
                startActivityForResult(intent, TO_PLAY_VIDEO);
                GridsumWebDissector.getInstance().trackEvent(this, "", "播放", "", 200, pairs);
                break;
            case 3:   //服务
                currentTabIndex = index;
                GridsumWebDissector.getInstance().trackEvent(this, "", "服务", "", 200, pairs);
                break;
            case 4:   //我的
                currentTabIndex = index;
                GridsumWebDissector.getInstance().trackEvent(this, "", "我的", "", 200, pairs);
                break;
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {

        exit();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    //退出时的时间
    private long mExitTime;

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(MainActivity.this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            manager.restartPackage(getPackageName());
//            if (showingFragment == null || !showingFragment.hasShowPlayer()) {
//            BasePlayerView.releaseAllVideos();
//            }
//            if (showingFragment != null) {
//                showingFragment.willDoExit();
//            }
//            Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);
//            mHomeIntent.addCategory(Intent.CATEGORY_HOME);
//            mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
//                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//            startActivity(mHomeIntent);
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        }
    }

//    /**
//     * 初始化请求服务城市配置数据
//     */
//    private void getServiceConfig() {
//        NetUtils.getNetAdapter().getServiceConfigData(getOwnerName(), ServiceFragment.configUrl, new AbsNetCallBack<ServiceConfigBean>(ServiceConfigBean.class) {
//            @Override
//            public void onSuc(ServiceConfigBean config) {
//                if (null != config) {
//                    getCityList(config.getUrl());
//                }
//            }
//
//            @Override
//            public void onEnd() {
//                super.onEnd();
//            }
//
//            @Override
//            public void onError(Throwable ex, String errorMsg) {
//                super.onError(ex, errorMsg);
//            }
//        });
//    }

    /**
     * 请求服务城市列表
     *
     * @param url
     */
    private void getCityList(String url) {
        if (TextUtils.isEmpty(url)) {

            return;
        }
        NetUtils.getNetAdapter().getServiceCityList(getOwnerName(), url, new AbsNetCallBack<ServiceCityListVo>(ServiceCityListVo.class) {
            @Override
            public void onSuc(ServiceCityListVo vo) {
                if (null != vo.getListInfo()) {
                    Cache.getInstance().setServiceCityList(vo.getListInfo());
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SharedPreferencesUtil.setParam(this, "FLOAT_AD", true);
    }

    /**
     * 请求用户相关数据，积分、邀请码等
     */
    private void initUserData() {
        if (UserManager.getInstance().isLogin()) {
            //TODO 查询用户积分数据
            ArrayMap<String, Object> p = new ArrayMap<>();
            p.put("userId", UserManager.getInstance().getUser().getPhoneNumber());
            p.put("token", UserManager.getInstance().getUser().getToken());
            NetUtils.getNetAdapter().postGetUserData(getOwnerName(), p, new AbsNetCallBack<UserInfoBean>(UserInfoBean.class) {
                @Override
                public void onSuc(UserInfoBean userInfoBean) {
                    Cache.getInstance().setUserInfo(userInfoBean);
                }

                @Override
                public void onEnd() {
                    super.onEnd();
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    super.onError(ex, errorMsg);
                }
            });
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TO_PLAY_VIDEO) {
            setCurrentTab(currentTabIndex);
        }
    }
}

